<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="设备id" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型id" prop="deviceTypeId">
        <el-input
          v-model="queryParams.deviceTypeId"
          placeholder="请输入设备类型id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="监测时间" prop="timestamp">
        <el-date-picker
          clearable
          v-model="queryParams.timestamp"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="监测值" prop="value">
        <el-input
          v-model="queryParams.value"
          placeholder="请输入监测值"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:data:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:data:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:data:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:data:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据id" align="center" prop="dataId" />
      <el-table-column label="设备id" align="center" prop="deviceId" />
      <el-table-column label="设备类型id" align="center" prop="deviceTypeId" />
      <el-table-column
        label="监测时间"
        align="center"
        prop="timestamp"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.timestamp, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="监测值" align="center" prop="value" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:data:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:data:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监测数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dataRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备id" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="设备类型id" prop="deviceTypeId">
          <el-input
            v-model="form.deviceTypeId"
            placeholder="请输入设备类型id"
          />
        </el-form-item>
        <el-form-item label="监测时间" prop="timestamp">
          <el-date-picker
            clearable
            v-model="form.timestamp"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择监测时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="监测值" prop="value">
          <el-input v-model="form.value" placeholder="请输入监测值" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="charts-container">
      <div class="chart-item">
        <div ref="gasChart" style="width: 100%; height: 250px"></div>
        <div class="chart-info">
          当前瓦斯浓度:
          <span class="current-value">{{ gasCurrentValue }}%</span>
          <p>(安全阈值: 0~1%)</p>
        </div>
      </div>
      <div class="chart-item">
        <div ref="temperatureChart" style="width: 100%; height: 250px"></div>
        <div class="chart-info">
          当前温度:
          <span class="current-value">{{ temperatureCurrentValue }}℃</span>
          <p>(安全阈值: 10℃~28℃)</p>
        </div>
      </div>
      <div class="chart-item">
        <div ref="humidityChart" style="width: 100%; height: 250px"></div>
        <div class="chart-info">
          当前湿度:
          <span class="current-value">{{ humidityCurrentValue }}%</span>
          <p>(安全阈值: 40%~70%)</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Data">
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/system/data";
import { ref, onMounted } from "vue";
import * as echarts from "echarts";

const { proxy } = getCurrentInstance();

const gasChart = ref(null);
const temperatureChart = ref(null);
const humidityChart = ref(null);
const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: null,
    deviceTypeId: null,
    timestamp: null,
    value: null,
    status: null,
  },
  rules: {
    timestamp: [{ required: true, message: "时间戳不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询监测数据列表 */
function getList() {
  loading.value = true;
  listData(queryParams.value).then((response) => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dataId: null,
    deviceId: null,
    deviceTypeId: null,
    timestamp: null,
    value: null,
    status: null,
  };
  proxy.resetForm("dataRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.dataId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加监测数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _dataId = row.dataId || ids.value;
  getData(_dataId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改监测数据";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dataRef"].validate((valid) => {
    if (valid) {
      if (form.value.dataId != null) {
        updateData(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addData(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dataIds = row.dataId || ids.value;
  proxy.$modal
    .confirm('是否确认删除监测数据编号为"' + _dataIds + '"的数据项？')
    .then(function () {
      return delData(_dataIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/data/export",
    {
      ...queryParams.value,
    },
    `data_${new Date().getTime()}.xlsx`
  );
}

getList();

// 初始化图表
const initChart = (
  chartRef,
  chartData,
  chartName,
  currentValueRef,
  xAxisDataRef
) => {
  if (!chartRef.value) return;
  const chartInstance = echarts.init(chartRef.value);
  const option = {
    title: {
      text: chartName + "检测",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: xAxisDataRef.value,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: chartName,
        type: "line",
        data: chartData,
      },
    ],
  };
  chartInstance.setOption(option);
  return chartInstance;
};

// 更新图表数据
const updateChartData = (chartInstance, chartData, currentValueRef) => {
  // 数据按时间顺序依次向前移动
  chartData.push(chartData.shift());
  // 更新图表
  chartInstance.setOption({
    series: [
      {
        data: chartData,
      },
    ],
  });
  // 更新当前值
  currentValueRef.value = chartData[chartData.length - 1];
};

// 更新时间轴数据
const updateTimeAxisData = (chartInstance, xAxisDataRef) => {
  // 时间轴数据按时间顺序依次向前移动
  xAxisDataRef.value.push(xAxisDataRef.value.shift());
  // 更新图表
  chartInstance.setOption({
    xAxis: {
      data: xAxisDataRef.value,
    },
  });
};

// 初始化图表数据
const gasData = ref([0.5, 1, 1.5, 1, 2, 1.5]);
const temperatureData = ref([20, 30, 35, 25, 20, 25]);
const humidityData = ref([40, 70, 60, 40, 50, 60]);

// 初始化时间轴数据
const gasXAxisData = ref(["00:00", "04:00", "8:00", "12:00", "16:00", "20:00"]);
const temperatureXAxisData = ref([
  "00:00",
  "04:00",
  "8:00",
  "12:00",
  "16:00",
  "20:00",
]);
const humidityXAxisData = ref([
  "00:00",
  "04:00",
  "8:00",
  "12:00",
  "16:00",
  "20:00",
]);

// 初始化图表实例
let gasChartInstance;
let temperatureChartInstance;
let humidityChartInstance;

// 初始化图表
onMounted(() => {
  gasChartInstance = initChart(
    gasChart,
    gasData.value,
    "瓦斯浓度",
    gasCurrentValue,
    gasXAxisData
  );
  temperatureChartInstance = initChart(
    temperatureChart,
    temperatureData.value,
    "温度",
    temperatureCurrentValue,
    temperatureXAxisData
  );
  humidityChartInstance = initChart(
    humidityChart,
    humidityData.value,
    "湿度",
    humidityCurrentValue,
    humidityXAxisData
  );
  getList();

  // 设置定时器每5秒更新一次数据点
  setInterval(() => {
    updateChartData(gasChartInstance, gasData.value, gasCurrentValue);
    updateChartData(
      temperatureChartInstance,
      temperatureData.value,
      temperatureCurrentValue
    );
    updateChartData(
      humidityChartInstance,
      humidityData.value,
      humidityCurrentValue
    );
  }, 5000);

  // 设置定时器每5分钟更新一次时间轴数据
  setInterval(() => {
    updateTimeAxisData(gasChartInstance, gasXAxisData);
    updateTimeAxisData(temperatureChartInstance, temperatureXAxisData);
    updateTimeAxisData(humidityChartInstance, humidityXAxisData);
  }, 5000); //
});

// 当前值
const gasCurrentValue = ref("0.5%");
const temperatureCurrentValue = ref("24℃");
const humidityCurrentValue = ref("55%");
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.charts-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.chart-item {
  width: 32%;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  box-sizing: border-box;
}

.chart-info {
  margin-top: 10px;
  font-size: 20px;
}

.current-value {
  color: green;
  font-weight: bold;
  border: 2px solid #007bff; /* 边框 */
  background-color: #f8f9fa; /* 底色 */
  padding: 5px; /* 内边距 */
  border-radius: 4px; /* 圆角 */
}

.chart-item p {
  color: red;
}
</style>
